//
//  InsuranceAddressViewController.m
//  PhotoAnnotate
//
//  Created by Bassem El-Tamimi on 26.01.11.
//  Copyright 2011 ePapyrus GmbH. All rights reserved.
//

#import "InsuranceAddressViewController.h"
#import "Insurance.h"
#import "InsuranceViewController.h"


#define FEATURES_TAB 1
#define INSURE_TAB 2
#define STATUS_TAB 3

@implementation InsuranceAddressViewController

@synthesize insuranceData, insuranceViewController, keyboardIsVisble;


#pragma mark -
#pragma mark view lifecycle methods

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = NSLocalizedString(@"INSURANCE_ADDRESS_TITLE", @"Address");
	self.navigationController.navigationBar.translucent = NO;
	self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
	
	// provide Save and Cancel buttons
	UIBarButtonItem* saveItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
																			  target:self action:@selector(saveFieldData:)];
	
	UIBarButtonItem* cancelItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
																			  target:self action:@selector(cancel:)];
	self.navigationItem.rightBarButtonItem = saveItem;
	self.navigationItem.leftBarButtonItem = cancelItem;

	[saveItem release];
	[cancelItem release];
	
	
	[scrollView setScrollEnabled:YES];
	[scrollView setFrame:CGRectMake(0,0,320,400)];
	[scrollView setContentSize:CGSizeMake(320,400)];
	
	[chooseAddressButton setTitle:NSLocalizedString(@"INSURANCE_ADDRESS_CHOOSE_ADDRESS_BUTTON", @"Choose Address") forState:UIControlStateNormal];
	
	[segmentedControl setTitle:NSLocalizedString(@"INSURANCE_ADDRESS_TITLE_MRS", @"Mrs.") forSegmentAtIndex:0];
	[segmentedControl setTitle:NSLocalizedString(@"INSURANCE_ADDRESS_TITLE_MR", @"Mr.") forSegmentAtIndex:1];
	[segmentedControl setTitle:NSLocalizedString(@"INSURANCE_ADDRESS_TITLE_COMPANY", @"Company") forSegmentAtIndex:2];
	
	[surnameField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_SURNAME", @"Surname or Company")];
	[nameField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_NAME", @"Name")];
	[streetAddressField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_STREET_ADDRESS", @"Street Address")];
	[postalCodeField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_POSTAL_CODE", @"Postal Code")];
	[cityField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_CITY", @"City")];
	[countryField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_COUNTRY", @"Country")];
	[emailField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_EMAIL", @"E-Mail")];
	[phoneField setPlaceholder:NSLocalizedString(@"INSURANCE_ADDRESS_PLACEHOLDER_PHONE_NUMBER", @"Phone Number")];
	
	// show data if any were saved
	[segmentedControl setSelectedSegmentIndex:[[insuranceData.address objectForKey:@"Title"] integerValue]];
	
	if ([insuranceData.address objectForKey:@"Surname"]) {
		[surnameField setText:[insuranceData.address objectForKey:@"Surname"]];
	}
	
	if ([insuranceData.address objectForKey:@"Name"]) {
		[nameField setText:[insuranceData.address objectForKey:@"Name"]];
	}

	if ([insuranceData.address objectForKey:@"StreetAddress"]) {
		[streetAddressField setText:[insuranceData.address objectForKey:@"StreetAddress"]];
	}
	
	if ([insuranceData.address objectForKey:@"PostalCode"]) {
		[postalCodeField setText:[insuranceData.address objectForKey:@"PostalCode"]];
	}
	
	if ([insuranceData.address objectForKey:@"City"]) {
		[cityField setText:[insuranceData.address objectForKey:@"City"]];
	}
	
	if ([insuranceData.address objectForKey:@"Country"]) {
		[countryField setText:[insuranceData.address objectForKey:@"Country"]];
	}
	
	if ([insuranceData.address objectForKey:@"EMail"]) {
		[emailField setText:[insuranceData.address objectForKey:@"EMail"]];
	}
	
	if ([insuranceData.address objectForKey:@"PhoneNumber"]) {
		[phoneField setText:[insuranceData.address objectForKey:@"PhoneNumber"]];
	}
	
}

- (void)cancel:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];

}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	[self.navigationController setNavigationBarHidden:NO animated:YES];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
												 name:UIKeyboardWillShowNotification object:self.view.window];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
												 name:UIKeyboardWillHideNotification object:self.view.window];
}

- (void)viewWillDisappear:(BOOL)animated
{	
	[super viewWillDisappear:animated];
	
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
	
	[self.navigationController setNavigationBarHidden:YES animated:NO];
	
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



#pragma mark -
#pragma mark keyboard notification methods

- (void)dismissKeyboard:(id)sender
{
	//[textView resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)aNotification 
{
	// the keyboard is showing so resize the table's height
	CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
	[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.view.frame;
    frame.size.height -= keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
	[scrollView setFrame:CGRectMake(0,0,320,460 - keyboardRect.size.height - [self.navigationController navigationBar].frame.size.height)];

}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    // the keyboard is hiding reset the table's height
	CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
	[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.view.frame;
    frame.size.height += keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
	[scrollView setContentSize:CGSizeMake(320,400)];
}


#pragma mark -
#pragma mark textField delegate methods

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
	
	return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	
	[textField resignFirstResponder];
	return YES;
}


#pragma mark -
#pragma mark AddressBook methods

- (IBAction)showPeoplePickerController:(id)sender
{
	ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
	// Display only a person's address
//	NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty], 
//							   [NSNumber numberWithInt:kABPersonEmailProperty],
//							   [NSNumber numberWithInt:kABPersonAddressProperty], nil];
	
	NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonAddressProperty], nil];
	
	picker.displayedProperties = displayedItems;
	// Show the picker 
	[self presentModalViewController:picker animated:YES];
    [picker release];	
}


#pragma mark ABPeoplePickerNavigationControllerDelegate methods
// Displays the information of a selected person
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
	
    return YES;
}


// Does not allow users to perform default actions such as dialing a phone number, when they select a person property.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person 
								property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
	
	ABMultiValueRef addresses = ABRecordCopyValue(person, property);
	
	if (property == kABPersonAddressProperty) {
		
		NSString* organization = (NSString *)ABRecordCopyValue(person, kABPersonOrganizationProperty);
		
		NSString* firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
		
		NSString* surname = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
		
		CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);
		
		
		//check if the selected contact is a company
		if (recordType == kABPersonKindOrganization) {
			surnameField.text = organization;
			[segmentedControl setSelectedSegmentIndex:2];
		} else {
			nameField.text = firstName;
			surnameField.text = surname;
		}
		
		CFRelease(recordType);
		
		ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
		
		phoneField.text = (NSString *)ABMultiValueCopyValueAtIndex(multi, 0);
		
		CFRelease(multi);
		
		multi = ABRecordCopyValue(person, kABPersonEmailProperty);
		
		emailField.text = (NSString *)ABMultiValueCopyValueAtIndex(multi, 0);
		
		CFRelease(multi);
		
	
		
        NSArray *theArray = [(id)ABMultiValueCopyArrayOfAllValues(addresses) autorelease];
		
        const NSUInteger theIndex = ABMultiValueGetIndexForIdentifier(addresses, identifier);
		
		NSDictionary *theDict = [theArray objectAtIndex:theIndex];
		
		streetAddressField.text = [theDict objectForKey:(NSString *)kABPersonAddressStreetKey];
		cityField.text = [theDict objectForKey:(NSString *)kABPersonAddressCityKey];
		postalCodeField.text = [theDict objectForKey:(NSString *)kABPersonAddressZIPKey];
		countryField.text = [theDict objectForKey:(NSString *)kABPersonAddressCountryKey];
		
		
		[organization release];
		[firstName release];
		[surname release];
		
		
		[ self dismissModalViewControllerAnimated:YES ];
		CFRelease(addresses);

        return NO;
		
	} else {
		CFRelease(addresses);

		return NO;
	}

	
	
	CFRelease(addresses);
	
    return YES;
}


// Dismisses the people picker and shows the application when users tap Cancel. 
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker;
{
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark ABPersonViewControllerDelegate methods
// Does not allow users to perform default actions such as dialing a phone number, when they select a contact property.
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person 
					property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue
{
	return NO;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/



#pragma mark -
#pragma mark memory management methods


- (void)saveFieldData:(id)sender
{
	
	[insuranceData.address setObject:[NSNumber numberWithInt:[segmentedControl selectedSegmentIndex]] forKey:@"Title"];
	
	if (surnameField.text != nil) {
		[insuranceData.address setObject:surnameField.text forKey:@"Surname"];
	}
	
	if (nameField.text != nil) {
		[insuranceData.address setObject:nameField.text forKey:@"Name"];
	}
	
	if (streetAddressField.text != nil) {
		[insuranceData.address setObject:streetAddressField.text forKey:@"StreetAddress"];
	}
	
	if (postalCodeField.text != nil) {
		[insuranceData.address setObject:postalCodeField.text forKey:@"PostalCode"];
	}
	
	if (cityField.text != nil) {
		[insuranceData.address setObject:cityField.text forKey:@"City"];
	}
	
	if (countryField.text != nil) {
		[insuranceData.address setObject:countryField.text forKey:@"Country"];
	}
	
	if (emailField.text != nil) {
		
		NSString *email = [emailField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
		
//		[insuranceData.address setObject:emailField.text forKey:@"EMail"];
		[insuranceData.address setObject:email forKey:@"EMail"];

	}
	
	if (phoneField.text != nil) {
		[insuranceData.address setObject:phoneField.text forKey:@"PhoneNumber"];
	}
	
	[self.insuranceData updatePropertyListData];
	[self.insuranceData saveChanges];
	
	[self.navigationController popViewControllerAnimated:YES];
	
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)dealloc {
    [super dealloc];
}


@end
